from device.models import Device
from device.serializers import DeviceSerializer
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.filters import OrderingFilter
from common.response import JsonResponse
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from common.constant import CODE_PARAMETER_ERROR, MSG_PARAMETER_ERROR
from channels.layers import get_channel_layer
from communication.consumers import device_state_change_group
from user.authentication_module import TokenAuth
from communication.consumers import sync_change_device_state


channel_layer = get_channel_layer()


async def change_device_state():

    await channel_layer.group_send(
        device_state_change_group, {"type": "deivce_change"})


class DeviceViewSet(viewsets.ReadOnlyModelViewSet):
    authentication_classes = [TokenAuth]
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer
    filter_backends = [OrderingFilter]
    ordering_fields = ('state',)


class DeviceCreateViewSet(APIView):
    """
        生成device，如果没有设备直接创建，可以修改name
    """

    def post(self, request):
        try:
            name = request.data['name']
            sn = request.data['sn']
            brand = request.data['brand']
            version = request.data['version']
        except Exception:
            return JsonResponse(data=None, code=CODE_PARAMETER_ERROR, message=MSG_PARAMETER_ERROR)
        try:
            device = Device.objects.get(sn=sn)
            if name and device.name != name:
                device.name = name
                sync_change_device_state()
            if(device.version != version):
                device.version = version
        except Device.DoesNotExist:
            device = Device(name=name, brand=brand,
                            sn=sn, version=version)
        device.save()
        change_device_state()
        return Response(DeviceSerializer(device).data)
